import { useRequest } from 'ahooks'
import {
  forwardRef,
  useContext,
  useEffect,
  useImperativeHandle,
  useRef,
  useState
} from 'react'
import CountUp from 'react-countup'

import { BarModule } from '../../Bar'
import { DomicileMap } from '../../DomicileMap'
import { MinPre } from '../../MinPre'
import { ModuleTitle } from '../../ModuleTitle'
import { ContentTsx } from '../../contentTsx'
import {
  colorLinearData,
  getAgeData,
  getDriverData,
  sudentCardDate
} from '../../data'
import type { SwitchAndIntervalRef } from '../../interface'
import { generateCountArray } from '../../utils'

interface DriverPieProps {
  updateEndTotalDirvers: (newEndTotalDirvers: number) => void
}

const DriverPie = forwardRef<SwitchAndIntervalRef, DriverPieProps>(
  (props, ref) => {
    const { updateEndTotalDirvers } = props
    const { selectedAssociationItem, refreshFlag } = useContext(ContentTsx)
    const [optionData, setOptionData] = useState<any>()
    const MinPreRef = useRef<{ resize: () => void }>(null)
    const BarRef = useRef<{ resize: () => void }>(null)

    const [totalDirvers, setTotalDirvers] = useState<number>(0) //司机总数
    const totalDirversRef = useRef<number>(0)
    const [prevTotalDirvers, setPrevTotalDirvers] = useState<number>(0)
    const [endTotalDirvers, setEndTotalDirvers] = useState<number>(0)
    const prevTotalDirversRef = useRef<number>(0)
    const endTotalDirversRef = useRef<number>(0)

    const [workingDrivers, setWorkingDrivers] = useState<number>(0) //今日上岗司机
    const workingDriversRef = useRef<number>(0)
    const [prevWorkingDrivers, setPrevWorkingDrivers] = useState<number>(0)
    const [endWorkingDrivers, setEndWorkingDrivers] = useState<number>(0)
    const prevWorkingDriversRef = useRef<number>(0)
    const endWorkingDriversRef = useRef<number>(0)

    const [drivingDrivers, setDrivingDrivers] = useState<number>(0) //今日在途司机
    const drivingDriversRef = useRef<number>(0)
    const [prevDrivingDrivers, setPrevDrivingDrivers] = useState<number>(0)
    const [endDrivingDrivers, setEndDrivingDrivers] = useState<number>(0)
    const prevDrivingDriversRef = useRef<number>(0)
    const endDrivingDriversRef = useRef<number>(0)

    // timeout
    const totalDirversTimeoutIdRef = useRef<any>()
    const workingDriversTimeoutIdRef = useRef<any>()
    const drivingDriversTimeoutIdRef = useRef<any>()

    //数据/时间 分组
    const totalDirversUpGroupRef = useRef<{
      countGroup: number[]
      timeGroup: number[]
    }>({
      countGroup: [],
      timeGroup: []
    })
    const workingDriversUpGroupRef = useRef<{
      countGroup: number[]
      timeGroup: number[]
    }>({
      countGroup: [],
      timeGroup: []
    })
    const drivingDriversUpGroupRef = useRef<{
      countGroup: number[]
      timeGroup: number[]
    }>({
      countGroup: [],
      timeGroup: []
    })

    const totalDirversUpGroupIndexRef = useRef<number>(0)
    const workingDriversUpGroupIndexRef = useRef<number>(0)
    const drivingDriversUpGroupIndexRef = useRef<number>(0)

    // const TestArrayRef = useRef<number[]>([2800, 3200, 1600])

    function clearCountUp() {
      if (totalDirversTimeoutIdRef.current) {
        clearTimeout(totalDirversTimeoutIdRef.current)
      }
      if (workingDriversTimeoutIdRef.current) {
        clearTimeout(workingDriversTimeoutIdRef.current)
      }

      if (drivingDriversTimeoutIdRef.current) {
        clearTimeout(drivingDriversTimeoutIdRef.current)
      }
    }

    //司机总数
    function _recursionTotalSetStartEndCount(gorupIndex: number) {
      // console.log("--totalDirversUpGroupIndexRef.current---:", totalDirversUpGroupIndexRef.current)
      if (gorupIndex > totalDirversUpGroupRef.current.countGroup.length - 1) {
        if (totalDirversTimeoutIdRef.current) {
          clearTimeout(totalDirversTimeoutIdRef.current)
        }
        if (endTotalDirversRef.current !== totalDirversRef.current) {
          // throw new Error('accrulAddCount!==count');
          console.error(
            `endTotalDirversRef.current 【${endTotalDirversRef.current}】!==totalDirversRef 【${totalDirversRef.current}】`
          )
        }
        return
      }

      const timeoutTime = Math.max(
        1,
        totalDirversUpGroupRef.current.timeGroup[gorupIndex] - 1
      ) //CountUp duration需要1s

      if (totalDirversTimeoutIdRef.current) {
        clearTimeout(totalDirversTimeoutIdRef.current)
      }
      totalDirversTimeoutIdRef.current = setTimeout(() => {
        if (gorupIndex === 0) {
          //初始化时是从1开始的，以后每次更新是从0开始的
          prevTotalDirversRef.current = endTotalDirversRef.current
        } else if (gorupIndex > 0) {
          prevTotalDirversRef.current +=
            totalDirversUpGroupRef.current.countGroup[gorupIndex - 1]
        }
        setPrevTotalDirvers(prevTotalDirversRef.current)

        const currEndCount =
          totalDirversUpGroupRef.current.countGroup[gorupIndex] +
          prevTotalDirversRef.current
        endTotalDirversRef.current = currEndCount
        // console.log(
        //   "--prevTotalDirversRef.current--endTotalDirversRef.current--:",
        //   prevTotalDirversRef.current,
        //   currEndCount
        // )
        setEndTotalDirvers(currEndCount)
        updateEndTotalDirvers(currEndCount)
      }, timeoutTime * 1000)
    }

    const handleTotalDriversCountUpEnd = () => {
      totalDirversUpGroupIndexRef.current += 1
      _recursionTotalSetStartEndCount(totalDirversUpGroupIndexRef.current)
    }

    //上岗司机
    function _recursionWorkingSetStartEndCount(gorupIndex: number) {
      if (gorupIndex > workingDriversUpGroupRef.current.countGroup.length - 1) {
        if (workingDriversTimeoutIdRef.current) {
          clearTimeout(workingDriversTimeoutIdRef.current)
        }
        if (endWorkingDriversRef.current !== workingDriversRef.current) {
          console.error(
            `endWorkingDriversRef.current 【${endWorkingDriversRef.current}】!==workingDriversRef.current 【${workingDriversRef.current}】`
          )
        }
        return
      }
      const timeoutTime = Math.max(
        1,
        workingDriversUpGroupRef.current.timeGroup[gorupIndex] - 1
      )
      if (workingDriversTimeoutIdRef.current) {
        clearTimeout(workingDriversTimeoutIdRef.current)
      }
      workingDriversTimeoutIdRef.current = setTimeout(() => {
        if (gorupIndex === 0) {
          //初始化时是从1开始的，以后每次更新是从0开始的
          prevWorkingDriversRef.current = endWorkingDriversRef.current
        } else if (gorupIndex > 0) {
          prevWorkingDriversRef.current +=
            workingDriversUpGroupRef.current.countGroup[gorupIndex - 1]
        }
        setPrevWorkingDrivers(prevWorkingDriversRef.current)

        const currEndCount =
          workingDriversUpGroupRef.current.countGroup[gorupIndex] +
          prevWorkingDriversRef.current
        endWorkingDriversRef.current = currEndCount
        setEndWorkingDrivers(currEndCount)
      }, timeoutTime * 1000)
    }

    const handleWorkingDriversCountUpEnd = () => {
      workingDriversUpGroupIndexRef.current += 1
      _recursionWorkingSetStartEndCount(workingDriversUpGroupIndexRef.current)
    }

    //在途司机
    function _recursionDrivingSetStartEndCount(gorupIndex: number) {
      if (gorupIndex > drivingDriversUpGroupRef.current.countGroup.length - 1) {
        if (drivingDriversTimeoutIdRef.current) {
          clearTimeout(drivingDriversTimeoutIdRef.current)
        }
        if (endDrivingDriversRef.current !== drivingDriversRef.current) {
          console.error(
            `endDrivingDriversRef.current 【${endDrivingDriversRef.current}】!==drivingDriversRef.current 【${drivingDriversRef.current}】`
          )
        }
        return
      }
      const timeoutTime = Math.max(
        1,
        drivingDriversUpGroupRef.current.timeGroup[gorupIndex] - 1
      )
      if (drivingDriversTimeoutIdRef.current) {
        clearTimeout(drivingDriversTimeoutIdRef.current)
      }
      drivingDriversTimeoutIdRef.current = setTimeout(() => {
        if (gorupIndex === 0) {
          //初始化时是从1开始的，以后每次更新是从0开始的
          prevDrivingDriversRef.current = endDrivingDriversRef.current
        } else if (gorupIndex > 0) {
          prevDrivingDriversRef.current +=
            drivingDriversUpGroupRef.current.countGroup[gorupIndex - 1]
        }
        setPrevDrivingDrivers(prevDrivingDriversRef.current)

        const currEndCount =
          drivingDriversUpGroupRef.current.countGroup[gorupIndex] +
          prevDrivingDriversRef.current
        endDrivingDriversRef.current = currEndCount
        setEndDrivingDrivers(currEndCount)
      }, timeoutTime * 1000)
    }

    const handleDrivingDirversCountUpEnd = () => {
      //初始化CountUp.start === 0 && CountUp.end === 0 时也会在duration 1s之后执行onEnd回调函数
      drivingDriversUpGroupIndexRef.current += 1
      _recursionDrivingSetStartEndCount(drivingDriversUpGroupIndexRef.current)
    }

    //初始化/切换协会时 获取数据
    function _initialOrSwitchAssociation(
      type: 'inital' | 'switchAssociation',
      associationKey: string
    ) {
      if (type === 'switchAssociation') {
        clearCountUp()
        setTotalDirvers(0) //司机总数
        totalDirversRef.current = 0
        setPrevTotalDirvers(0)
        setEndTotalDirvers(0)
        prevTotalDirversRef.current = 0
        endTotalDirversRef.current = 0

        setWorkingDrivers(0) //今日上岗司机
        workingDriversRef.current = 0
        setPrevWorkingDrivers(0)
        setEndWorkingDrivers(0)
        prevWorkingDriversRef.current = 0
        endWorkingDriversRef.current = 0

        setDrivingDrivers(0) //今日在途司机
        drivingDriversRef.current = 0
        setPrevDrivingDrivers(0)
        setEndDrivingDrivers(0)
        prevDrivingDriversRef.current = 0
        endDrivingDriversRef.current = 0
        totalDirversUpGroupRef.current = {
          countGroup: [],
          timeGroup: []
        }
        workingDriversUpGroupRef.current = {
          countGroup: [],
          timeGroup: []
        }
        drivingDriversUpGroupRef.current = {
          countGroup: [],
          timeGroup: []
        }
        totalDirversUpGroupIndexRef.current = 0
        workingDriversUpGroupIndexRef.current = 0
        drivingDriversUpGroupIndexRef.current = 0
      }
      getDriverData({ entId: associationKey })
        .then((data) => {
          setOptionData(data)
          const { allSum = 0, onlineSum = 0, zaiTuSum = 0 } = data
          setTotalDirvers(allSum)
          setWorkingDrivers(onlineSum)
          setDrivingDrivers(zaiTuSum)
          totalDirversRef.current = allSum
          workingDriversRef.current = onlineSum
          drivingDriversRef.current = zaiTuSum

          if (allSum > 0) {
            endTotalDirversRef.current = allSum
            setEndTotalDirvers(allSum)
            updateEndTotalDirvers(allSum)
          }

          if (onlineSum > 0) {
            endWorkingDriversRef.current = onlineSum
            setEndWorkingDrivers(onlineSum)
          }

          if (zaiTuSum > 0) {
            endDrivingDriversRef.current = zaiTuSum
            setEndDrivingDrivers(zaiTuSum)
          }
        })
        .catch((err: any) => {
          console.error(
            '--DriverPice--_initialOrSwitchAssociation--getDriverData--err--:',
            err
          )
        })
    }

    //5分钟刷新时
    function _intervalRefresh() {
      clearCountUp()
      getDriverData({ entId: selectedAssociationItem.key })
        .then((data) => {
          setOptionData(data)
          const { allSum = 0, onlineSum = 0, zaiTuSum = 0 } = data

          // const { onlineSum = 0, zaiTuSum = 0 } = data;
          // const allSum = TestArrayRef.current.splice(0, 1)[0];

          setTotalDirvers(allSum)
          setWorkingDrivers(onlineSum)
          setDrivingDrivers(zaiTuSum)
          totalDirversRef.current = allSum
          workingDriversRef.current = onlineSum
          drivingDriversRef.current = zaiTuSum
          //司机总数
          const totalDriversCountDiff = allSum - endTotalDirversRef.current
          if (totalDriversCountDiff === 0) {
            return
          } else {
            totalDirversUpGroupIndexRef.current = 0
            totalDirversUpGroupRef.current = generateCountArray(
              endTotalDirversRef.current,
              allSum
            )
            // console.log('--allSum--endTotalDirversRef.current-- totalDirversUpGroupRef.current--:', allSum, endTotalDirversRef.current, totalDirversUpGroupRef.current)
            if (totalDriversCountDiff < 0) {
              totalDirversUpGroupRef.current = {
                countGroup: totalDirversUpGroupRef.current.countGroup.map(
                  (count) => count * -1
                ),
                timeGroup: totalDirversUpGroupRef.current.timeGroup
              }
            }
            _recursionTotalSetStartEndCount(totalDirversUpGroupIndexRef.current)
          }

          //在岗司机
          const workingDriversCountDiff =
            onlineSum - endWorkingDriversRef.current
          if (workingDriversCountDiff === 0) {
            return
          } else {
            workingDriversUpGroupIndexRef.current = 0
            workingDriversUpGroupRef.current = generateCountArray(
              endWorkingDriversRef.current,
              onlineSum
            )
            if (workingDriversCountDiff < 0) {
              workingDriversUpGroupRef.current = {
                countGroup: workingDriversUpGroupRef.current.countGroup.map(
                  (count) => count * -1
                ),
                timeGroup: workingDriversUpGroupRef.current.timeGroup
              }
            }
            _recursionWorkingSetStartEndCount(
              workingDriversUpGroupIndexRef.current
            )
          }

          //在途司机
          const drivingDriversCountDiff =
            zaiTuSum - endDrivingDriversRef.current
          if (drivingDriversCountDiff === 0) {
            return
          } else {
            drivingDriversTimeoutIdRef.current = 0
            drivingDriversUpGroupRef.current = generateCountArray(
              endDrivingDriversRef.current,
              zaiTuSum
            )
            if (drivingDriversCountDiff < 0) {
              drivingDriversUpGroupRef.current = {
                countGroup: drivingDriversUpGroupRef.current.countGroup.map(
                  (count) => count * -1
                ),
                timeGroup: drivingDriversUpGroupRef.current.timeGroup
              }
            }
            _recursionDrivingSetStartEndCount(
              drivingDriversTimeoutIdRef.current
            )
          }
        })
        .catch((err: any) => {
          console.error(
            '--DriverPice--_intervalRefresh--getDriverData--err--:',
            err
          )
        })
    }

    useImperativeHandle(ref, () => ({
      switchAssociation: (newAssociationId) => {
        _initialOrSwitchAssociation('switchAssociation', newAssociationId)
      },
      intervalRefresh: _intervalRefresh,
      resize: () => {
        if (MinPreRef.current) {
          MinPreRef.current.resize()
        }
        if (BarRef.current) {
          BarRef.current.resize()
        }
      }
    }))

    useEffect(() => {
      _initialOrSwitchAssociation('inital', selectedAssociationItem.key)
      return () => {
        clearCountUp()
      }
    }, [])

    const { data: sudentCard } = useRequest(
      async () => {
        const data = await sudentCardDate({
          entId: selectedAssociationItem.key
        })
        return data
      },
      {
        refreshDeps: [selectedAssociationItem.key, refreshFlag]
      }
    )
    // 年龄分析数据
    type dataType = {
      xData: any
      yData: any
      yInfoData: any
    }
    const [echartData, setEchartData] = useState<dataType>({
      xData: [],
      yData: [],
      yInfoData: []
    })
    useRequest(
      async () => {
        const data = await getAgeData({ entId: selectedAssociationItem.key })
        const x = [
          '20-24',
          '25-29',
          '30-34',
          '35-39',
          '40-44',
          '45-49',
          '50-54',
          '55-59',
          '60以上'
        ]
        const y: any[] = []
        const yInfoData: any[] = []
        x.map((v) => {
          let min: number | string
          let max: number | string
          if (v == '60以上') {
            min = 60
            max = 99999
          } else {
            min = v.split('-')[0]
            max = v.split('-')[1]
          }

          let value = 0
          const ageData = data.filter(
            (v: any) =>
              Number(min) <= Number(v.name) && Number(v.name) <= Number(max)
          )
          const yz: { age: string; value: number }[] = []
          ageData.map((v: any) => {
            value += v.value
            if (v.value > 0) {
              yz.push({ age: String(v.name), value: v.value })
            }
          })
          y.push(value)
          yInfoData.push(yz)
        })
        function checkArrayForZeros(arr: any) {
          for (let i = 0; i < arr.length; i++) {
            if (arr[i] !== 0) {
              return true // 如果发现不为0的元素，返回true
            }
          }
          return false // 如果所有元素都为0，返回false
        }
        const a = checkArrayForZeros(y)
        function deepCompare(obj1: any, obj2: any) {
          if (obj1 === obj2) return true

          if (
            typeof obj1 !== 'object' ||
            typeof obj2 !== 'object' ||
            obj1 === null ||
            obj2 === null
          )
            return false

          const keys1 = Object.keys(obj1)
          const keys2 = Object.keys(obj2)

          if (keys1.length !== keys2.length) return false

          for (const key of keys1) {
            if (!keys2.includes(key)) return false
            if (!deepCompare(obj1[key], obj2[key])) return false
          }

          return true
        }

        const b = {
          xData: x,
          yData: a ? y : undefined,
          yInfoData: yInfoData
        }

        const result = deepCompare(echartData, b)
        if (result) {
          return
        } else {
          setEchartData(b)
        }
      },
      {
        refreshDeps: [selectedAssociationItem.key, refreshFlag]
      }
    )

    return (
      <div
        className="bigscreen-module ms-module"
        style={{ height: '743px', overflow: 'hidden' }}
      >
        <ModuleTitle title={'司机数据分析'}></ModuleTitle>
        <div className="bigscreen-content" style={{ paddingTop: 14 }}>
          <div
            className="drvierCount flexr jub"
            style={{ minHeight: 53, maxHeight: 71, overflow: 'hidden' }}
          >
            <div style={{ width: '85px' }}>
              <div className="dr_count_num">
                <CountUp
                  start={prevTotalDirvers}
                  end={endTotalDirvers}
                  duration={1}
                  onEnd={handleTotalDriversCountUpEnd}
                />
              </div>
              <div className="dr_label">司机总数</div>
            </div>
            <div style={{ width: '85px' }}>
              <div className="dr_count_num">
                <CountUp
                  start={prevWorkingDrivers}
                  end={endWorkingDrivers}
                  duration={1}
                  onEnd={handleWorkingDriversCountUpEnd}
                />
              </div>
              <div className="dr_label">今日上岗司机</div>
            </div>
            <div style={{ width: '85px' }}>
              <div className="dr_count_num">
                <CountUp
                  start={prevDrivingDrivers}
                  end={endDrivingDrivers}
                  duration={1}
                  onEnd={handleDrivingDirversCountUpEnd}
                />
              </div>
              <div className="dr_label">今日在途司机</div>
            </div>
          </div>

          <div
            className="flexr alc"
            style={{
              marginTop: 16,
              marginBottom: 25,
              height: 70,
              overflow: 'hidden'
            }}
          >
            <div style={{ width: '190px' }}>
              <MinPre
                ref={MinPreRef}
                data={optionData?.sexKvs || []}
                color={colorLinearData.slice(0, 3)}
                title="性别"
              ></MinPre>
            </div>
            <div style={{ width: '30px', height: '100px' }}></div>
            <div>
              <MinPre
                ref={MinPreRef}
                data={sudentCard?.sgKvs || []}
                color={colorLinearData.slice(3, 6)}
                title="学习卡分析"
              ></MinPre>
            </div>
          </div>
          <LineP></LineP>
          <div style={{ margin: '16px 0', height: 139, overflow: 'hidden' }}>
            <BarModule
              title={'年龄分析'}
              data={echartData}
              barHeight={139}
              ref={BarRef}
            ></BarModule>
          </div>
          <LineP></LineP>
          <DomicileMap></DomicileMap>
        </div>
      </div>
    )
  }
)

export default DriverPie

function LineP() {
  return (
    <div className="line-radius">
      {/* <div className="line-pieicon"></div> */}
    </div>
  )
}
